﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Mvc.StarterSite.Controllers;
using MvcEngine.Mvc.Models.ViewModels;
using System.Web.Mvc;
using MvcEngine.Core;
using MvcEngine.Core.Common.Slugs;
using MvcEngine.Core.Repositories;
using System.Web;
using System.Web.Routing;
using MvcEngine.Core.Validation;
using System.Web.Mvc.Html;
using MvcEngine.Mvc.Filters;
using MvcEngine.Contact.Models;
using MvcEngine.Core.Content;
using MvcEngine.Core.Helpers;
using MvcEngine.Mvc.Extensions;
using MvcEngine.Core.Services;
using MvcEngine.Mvc.Controllers;

namespace MvcEngine.Contact.StarterSite.Controllers
{
    public class ContactController : SubController
    {
        public MvcEngineModel Index()
        {
            return new MvcEngineModel() { ViewName = "SendEmail" };
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [AntiForgeryValidationFilter]
        public MvcEngineModel SendEmail(int ctrId, MessageData msg)
        {
            if (ModelState.IsValid)
            {
                var pageContent = ContentManager.Current.GetPageContent(ctrId);
                Guard.ThrowIfNull(pageContent, string.Format("Page content {0} does not exist.", ctrId));
                ContactSettings settings = new ContactSettings(pageContent);

                string body = EmailSender.Current.GetMailBody("ContactTemplate", "name", msg.Name,
                    "email", msg.Email, "message", msg.Message, "ipAddress", Request.UserHostAddress,
                    "userAgent", Request.UserAgent);

                string title = EmailSender.Current.GetMailBody("ContactTemplateTitle", "subject", msg.Subject);
                if (!string.IsNullOrEmpty(settings.EmailSubjectPrefix))
                    title = settings.EmailSubjectPrefix + " - " + title;

                var smtpSettings = new EmailSettings()
                {
                    Email = settings.Email,
                    Host = settings.SmtpServer,
                    Password = settings.SmtpPassword,
                    Port = settings.SmtpServerPort,
                    UserName = settings.SmtpUserName
                };

                try
                {
                    EmailSender.Current.SendMail(smtpSettings, settings.Email, settings.SendTo, title, body);
                }
                catch (Exception)
                {
                    return new MvcEngineModel() { ViewName = "MessageSentFailed" };    
                }
                return new MvcEngineModel() { ViewName = "MessageSent" };
            }
            else
            {
                return Index();
            }
        }
    }
}
